package com.study.lu;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

public class ScheduleExecutorServiceTest {

//    public static void main(String[] args) {
//        ScheduleExecutorServiceTest test = new ScheduleExecutorServiceTest();
//        test.testAtFixedRate();
//    }
//
//    private ScheduledThreadPoolExecutor executor;


    private static class CardInfo {
        BigDecimal price = new BigDecimal(0.0);
        String name = "张三";
        int age = 5;
        Date birthdate = new Date();

        public void m() {}
    }

    private static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(50,
            new ThreadPoolExecutor.DiscardOldestPolicy());

    public static void main(String[] args) throws Exception {
        executor.setMaximumPoolSize(50);

        for (;;){
            modelFit();
            Thread.sleep(100);
        }
    }

    private static void modelFit(){
        List<CardInfo> taskList = getAllCardInfo();
        taskList.forEach(info -> {
            // do something
            executor.scheduleWithFixedDelay(() -> {
                //do sth with info
                info.m();

            }, 2, 3, TimeUnit.SECONDS);
        });
    }

    private static List<CardInfo> getAllCardInfo(){
        List<CardInfo> taskList = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            CardInfo ci = new CardInfo();
            taskList.add(ci);
        }

        return taskList;
    }

    public ScheduleExecutorServiceTest() {
        executor = new ScheduledThreadPoolExecutor(50,
                new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    public void testAtFixedRate() {
        executor.scheduleAtFixedRate(new Runnable() {

            public void run() {
                System.out.println("====");

                try {
                    int i = 1 / 0;
                    System.out.println("执行完毕");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 1000, 3000, TimeUnit.MILLISECONDS);
    }

    public void testWithFixedDelay() {
        executor.scheduleWithFixedDelay(new Runnable() {

            public void run() {
                System.out.println("====");
                try {
                    int i = 1 / 0;
                } catch (Exception e) {
                    e.printStackTrace();
                }
				/*
				try {
					Thread.sleep(10000);
					System.out.println("执行完毕");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				*/
            }
        }, 1000, 3000, TimeUnit.MILLISECONDS);
    }

}
